<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="合同名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同分类" prop="typeId">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择分类"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_CONTRACT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="到期时间" prop="expiredTime">
        <el-date-picker
          v-model="queryParams.expiredTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['school:contract:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['school:contract:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="合同名称" align="center" prop="name" />
      <el-table-column label="分类" align="center" prop="typeId">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SCHOOL_CONTRACT_TYPE" :value="scope.row.typeId" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="合同文件" align="center" prop="fileUrls" /> -->
      <el-table-column label="合同文件" align="center" prop="fileUrls" :show-overflow-tooltip="false">
          <template #default="scope">
            <FileListView :file-list="scope.row.fileUrls" />
          </template>
      </el-table-column>
      <el-table-column
        label="合同到期时间"
        align="center"
        prop="expiredTime"
        :formatter="dateFormatter2"
        width="180px"
      />
      <el-table-column label="合同关联用户" align="center" prop="userNames" />
      <el-table-column label="提前提醒天数" align="center" prop="notifyDays" />
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="排序" align="center" prop="sort" /> -->
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" fixed="right" width="160">
        <template #default="scope">
          <el-button
v-if="0 == scope.row.status"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['school:contract:update']"
          >
            编辑
          </el-button>
          <el-button
v-if="0 == scope.row.status"
            link
            type="success"
            @click="handleStore(scope.row.id,1)"
            v-hasPermi="['school:contract:update']"
          >
            归档
          </el-button>
          <el-button
v-if="1 == scope.row.status"
            link
            type="success"
            @click="handleStore(scope.row.id,0)"
            v-hasPermi="['school:contract:update']"
          >
            还原
          </el-button>
          <el-button
v-if="0 == scope.row.status"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['school:contract:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContractForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter , dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import { ContractApi, ContractVO } from '@/api/school/contract'
import ContractForm from './ContractForm.vue'
const route = useRoute()

/** 合同管理 列表 */
defineOptions({ name: 'SchoolContract' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ContractVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  typeId: undefined,
  expiredTime: [],
  status: 0,
  createTime: [],
})

//归档查询参数
const storeParams = reactive({
  id:0,
  status: 0,
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContractApi.getContractPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 归档按钮操作 */
const handleStore = async (id: number, status:number) => {
  try {
    // 二次确认
    const actionText = status === 1 ? '归档' : '还原';
    await message.confirm(`确定将此合同${actionText}吗？`);
    // 调用接口
    storeParams.id = id
    storeParams.status = status
    console.log(storeParams.id + '===' +storeParams.status);
    
    await ContractApi.storeContract(storeParams)
    message.success(t('common.success'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractApi.deleteContract(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractApi.exportContract(queryParams)
    download.excel(data, '合同管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 路由到 oper 映射关系
const pathToTypeMap = {
  '/school/contract/list': 0,
  '/school/contract/storeList': 1,
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(() => route.path, (path) => {
  console.log(path, '---path');
  
  // 匹配路径并赋值 assetType，如果没有匹配则设为默认值 0
  queryParams.status = pathToTypeMap[path] || 0
  console.log(queryParams.status, '---status');
  
}, {
  immediate: true  //立即执行一次
})

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>